package com.uniflow.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uniflow.entity.Permission;
import com.uniflow.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 权限服务层
 * 
 * @author uniflow
 * @since 1.0.0
 */
@Service
public class PermissionService {
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    /**
     * 分页查询权限
     */
    public IPage<Permission> getPermissionPage(int pageNum, int pageSize, String type, String parentId, Boolean enabled, String keyword) {
        Page<Permission> page = new Page<>(pageNum, pageSize);
        return permissionMapper.selectPermissionPage(page, type, parentId, enabled, keyword);
    }
    
    /**
     * 根据ID查询权限
     */
    public Permission getPermissionById(String id) {
        return permissionMapper.selectById(id);
    }
    
    /**
     * 根据权限代码查询
     */
    public Permission getPermissionByCode(String code) {
        return permissionMapper.selectByCode(code);
    }
    
    /**
     * 查询权限树结构
     */
    public List<Permission> getPermissionTree() {
        return permissionMapper.selectPermissionTree();
    }
    
    /**
     * 查询根权限列表
     */
    public List<Permission> getRootPermissions() {
        return permissionMapper.selectRootPermissions();
    }
    
    /**
     * 根据父级ID查询子权限
     */
    public List<Permission> getChildrenPermissions(String parentId) {
        return permissionMapper.selectByParentId(parentId);
    }
    
    /**
     * 根据类型查询权限
     */
    public List<Permission> getPermissionsByType(String type) {
        return permissionMapper.selectByType(type);
    }
    
    /**
     * 查询启用的权限列表
     */
    public List<Permission> getEnabledPermissions() {
        return permissionMapper.selectEnabledPermissions();
    }
    
    /**
     * 查询用户权限列表
     */
    public List<Permission> getUserPermissions(String userId) {
        return permissionMapper.selectUserPermissions(userId);
    }
    
    /**
     * 查询角色权限列表
     */
    public List<Permission> getRolePermissions(String roleId) {
        return permissionMapper.selectRolePermissions(roleId);
    }
    
    /**
     * 检查用户是否有指定权限
     */
    public boolean hasUserPermission(String userId, String permissionCode) {
        return permissionMapper.hasUserPermission(userId, permissionCode);
    }
    
    /**
     * 检查角色是否有指定权限
     */
    public boolean hasRolePermission(String roleId, String permissionCode) {
        return permissionMapper.hasRolePermission(roleId, permissionCode);
    }
    
    /**
     * 创建权限
     */
    @Transactional
    public Permission createPermission(Permission permission) {
        // 生成ID
        permission.setId(UUID.randomUUID().toString().replace("-", ""));
        
        // 设置创建时间
        LocalDateTime now = LocalDateTime.now();
        permission.setCreatedAt(now);
        permission.setUpdatedAt(now);
        
        // 检查权限代码是否重复
        if (permissionMapper.existsByCode(permission.getCode(), null)) {
            throw new RuntimeException("权限代码已存在");
        }
        
        // 设置默认值
        if (permission.getEnabled() == null) {
            permission.setEnabled(true);
        }
        if (permission.getSortOrder() == null) {
            permission.setSortOrder(0);
        }
        
        permissionMapper.insert(permission);
        return permission;
    }
    
    /**
     * 更新权限
     */
    @Transactional
    public Permission updatePermission(Permission permission) {
        // 检查权限是否存在
        Permission existingPermission = permissionMapper.selectById(permission.getId());
        if (existingPermission == null) {
            throw new RuntimeException("权限不存在");
        }
        
        // 检查权限代码是否重复
        if (permissionMapper.existsByCode(permission.getCode(), permission.getId())) {
            throw new RuntimeException("权限代码已存在");
        }
        
        // 设置更新时间
        permission.setUpdatedAt(LocalDateTime.now());
        
        permissionMapper.updateById(permission);
        return permission;
    }
    
    /**
     * 删除权限
     */
    @Transactional
    public void deletePermission(String id) {
        // 检查是否有子权限
        if (permissionMapper.hasChildren(id)) {
            throw new RuntimeException("该权限下存在子权限，无法删除");
        }
        
        permissionMapper.deleteById(id);
    }
    
    /**
     * 批量删除权限
     */
    @Transactional
    public void deletePermissions(List<String> ids) {
        for (String id : ids) {
            deletePermission(id);
        }
    }
    
    /**
     * 批量更新权限状态
     */
    @Transactional
    public void batchUpdateEnabled(List<String> ids, Boolean enabled) {
        permissionMapper.batchUpdateEnabled(ids, enabled);
    }
    
    /**
     * 查询权限统计信息
     */
    public Map<String, Object> getPermissionStats() {
        return permissionMapper.selectPermissionStats();
    }
    
    /**
     * 查询权限类型分布
     */
    public List<Map<String, Object>> getTypeDistribution() {
        return permissionMapper.selectTypeDistribution();
    }
    
    /**
     * 查询权限使用统计
     */
    public List<Map<String, Object>> getUsageStats() {
        return permissionMapper.selectUsageStats();
    }
    
    /**
     * 查询最近创建的权限
     */
    public List<Permission> getRecentCreated(Integer limit) {
        return permissionMapper.selectRecentCreated(limit);
    }
    
    /**
     * 查询未使用的权限
     */
    public List<Permission> getUnusedPermissions() {
        return permissionMapper.selectUnusedPermissions();
    }
    
    /**
     * 查询权限路径
     */
    public List<Permission> getPermissionPath(String permissionId) {
        return permissionMapper.selectPermissionPath(permissionId);
    }
    
    /**
     * 查询权限详情（包含层级信息）
     */
    public Permission getPermissionWithHierarchy(String id) {
        return permissionMapper.selectWithHierarchy(id);
    }
    
    /**
     * 查询菜单权限树
     */
    public List<Permission> getMenuPermissionTree() {
        return permissionMapper.selectMenuPermissionTree();
    }
    
    /**
     * 查询操作权限列表
     */
    public List<Permission> getOperationPermissions(String resource) {
        return permissionMapper.selectOperationPermissions(resource);
    }
    
    /**
     * 查询数据权限列表
     */
    public List<Permission> getDataPermissions() {
        return permissionMapper.selectDataPermissions();
    }
    
    /**
     * 批量创建权限
     */
    @Transactional
    public void createPermissions(List<Permission> permissions) {
        LocalDateTime now = LocalDateTime.now();
        for (Permission permission : permissions) {
            permission.setId(UUID.randomUUID().toString().replace("-", ""));
            permission.setCreatedAt(now);
            permission.setUpdatedAt(now);
            
            if (permission.getEnabled() == null) {
                permission.setEnabled(true);
            }
            if (permission.getSortOrder() == null) {
                permission.setSortOrder(0);
            }
        }
        permissionMapper.insertBatch(permissions);
    }
    
    /**
     * 查询权限继承关系
     */
    public List<Map<String, Object>> getInheritanceRelations(String permissionId) {
        return permissionMapper.selectInheritanceRelations(permissionId);
    }
    
    /**
     * 查询权限冲突检测
     */
    public List<Map<String, Object>> getConflictPermissions(String userId) {
        return permissionMapper.selectConflictPermissions(userId);
    }
    
    /**
     * 查询权限审计信息
     */
    public List<Map<String, Object>> getAuditInfo(String permissionId, String startDate, String endDate) {
        return permissionMapper.selectAuditInfo(permissionId, startDate, endDate);
    }
    
    /**
     * 初始化系统默认权限
     */
    @Transactional
    public void initDefaultPermissions() {
        // 检查是否已初始化
        List<Permission> existingPermissions = permissionMapper.selectRootPermissions();
        if (!existingPermissions.isEmpty()) {
            return;
        }
        
        // 创建默认权限结构
        List<Permission> defaultPermissions = createDefaultPermissionStructure();
        createPermissions(defaultPermissions);
    }
    
    /**
     * 创建默认权限结构
     */
    private List<Permission> createDefaultPermissionStructure() {
        // 这里可以定义系统的默认权限结构
        // 包括菜单权限、操作权限、数据权限等
        return Arrays.asList(
            // 系统管理
            createPermission("system", "系统管理", "menu", null, null, null, 1),
            createPermission("system:user", "用户管理", "menu", "system", null, null, 2),
            createPermission("system:user:read", "查看用户", "operation", "system:user", "user", "read", 3),
            createPermission("system:user:write", "编辑用户", "operation", "system:user", "user", "write", 3),
            createPermission("system:role", "角色管理", "menu", "system", null, null, 2),
            createPermission("system:role:read", "查看角色", "operation", "system:role", "role", "read", 3),
            createPermission("system:role:write", "编辑角色", "operation", "system:role", "role", "write", 3),
            createPermission("system:permission", "权限管理", "menu", "system", null, null, 2),
            createPermission("system:permission:read", "查看权限", "operation", "system:permission", "permission", "read", 3),
            createPermission("system:permission:write", "编辑权限", "operation", "system:permission", "permission", "write", 3)
        );
    }
    
    /**
     * 创建权限对象
     */
    private Permission createPermission(String code, String name, String type, String parentCode, String resource, String action, int level) {
        Permission permission = new Permission();
        permission.setCode(code);
        permission.setName(name);
        permission.setType(type);
        permission.setResource(resource);
        permission.setAction(action);
        permission.setEnabled(true);
        permission.setSortOrder(0);
        
        // 如果有父级权限，需要查询父级ID
        if (parentCode != null) {
            Permission parent = permissionMapper.selectByCode(parentCode);
            if (parent != null) {
                permission.setParentId(parent.getId());
            }
        }
        
        return permission;
    }
}